<template>
  <div>
    <el-card>
      <template #header>
        <h2>外出登记</h2>
      </template>
      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="客户姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchData">查询</el-button>
          <el-button type="primary" @click="viewRegistration">查看外出申请</el-button>
        </el-form-item>
      </el-form>

      <div class="table-title">
        <h3>客户信息</h3>
      </div>
      <!-- 客户列表 -->
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="客户姓名" width="100" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column label="性别" width="80">
          <template #default="{ row }">
            <span>{{ row.gender === 0 ? '男' : '女' }}</span>
          </template>
        </el-table-column>
		<el-table-column prop="roomNumber" label="房间号" width="60" />
        <el-table-column prop="bedNumber" label="床号" />
        <el-table-column prop="careLevelName" label="护理级别" width="120" />
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="add(row)">
              添加外出申请
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="loadData"
        @size-change="loadData"
      />
    </el-card>

    <!-- 抽屉：添加外出申请 -->
    <el-drawer v-model="drawerVisible" title="添加外出申请" size="40%">
      <el-form :model="formData" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="客户姓名">
          <el-input v-model="formData.customerName" disabled />
        </el-form-item>
        <el-form-item label="外出事由" prop="reason">
          <el-input v-model="formData.reason" placeholder="请输入事由" />
        </el-form-item>
        <el-form-item label="外出时间" prop="outTime">
          <el-date-picker
            v-model="formData.outTime"
            type="datetime"
            placeholder="选择外出时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="预计回院时间" prop="expectedReturn">
          <el-date-picker
            v-model="formData.expectedReturn"
            type="datetime"
            placeholder="选择预计回院时间"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 新增字段：陪同人姓名 -->
        <el-form-item label="陪同人姓名" prop="companionName">
          <el-input v-model="formData.companionName" placeholder="请输入陪同人姓名" />
        </el-form-item>
        <!-- 新增字段：陪同人关系 -->
        <el-form-item label="陪同人关系" prop="companionRelation">
          <el-input
            v-model="formData.companionRelation"
            placeholder="例如：子女/朋友/保姆"
          />
        </el-form-item>
        <!-- 新增字段：陪同人电话 -->
        <el-form-item label="陪同人电话" prop="companionPhone">
          <el-input
            v-model="formData.companionPhone"
            placeholder="请输入陪同人电话"
          />
        </el-form-item>

        <el-form-item label="审批状态">
          <el-radio-group v-model="formData.status">
            <el-radio :value="'已提交'">已提交</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交申请</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, inject } from 'vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import { jwtDecode } from 'jwt-decode'
import { useRouter } from 'vue-router'

const axios = inject('axios')
const router = useRouter()
const formRef = ref(null)

// 健康管家ID
const nurseId = ref('')
  const init = ()=>{
      let token=sessionStorage.getItem('token');
      const payload = jwtDecode(token);
      const user = JSON.parse(payload.mobileJson)
      nurseId.value=user.id;
      console.log(nurseId.value);
  }
  init();
// 搜索模型
const searchForm = reactive({ name: '' })

// 客户列表 & 分页
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

function loadData() {
  axios
    .post(
      'CheckOutRegistrationController/searchClient',
      qs.stringify({
        healthManagerId: nurseId.value,
        clientName: searchForm.name,
        cur: currentPage.value,
        number: pageSize.value
      })
    )
    .then((res) => {
      const rb = res.data
      if (rb.status === 200) {
        tableData.value = rb.data
        total.value = rb.total
      } else {
        ElMessage.error('加载失败：' + rb.message)
      }
    })
}

watch([currentPage, pageSize], loadData)
loadData()

function searchData() {
  currentPage.value = 1
  loadData()
}

function viewRegistration() {
  router.push({ path: '/OutboundApplication', query: { nurseId: nurseId.value } })
}

// 抽屉 & 表单数据
const drawerVisible = ref(false)
const formData = reactive({
  customerId: null,
  customerName: '',
  reason: '',
  outTime: '',
  expectedReturn: '',
  companionName: '',
  companionRelation: '',
  companionPhone: '',
  status: '已提交'
})

// 表单校验规则（可选）
const rules = {
  reason: [{ required: true, message: '请输入外出事由', trigger: 'blur' }],
  outTime: [{ required: true, message: '请选择外出时间', trigger: 'change' }],
  expectedReturn: [
    { required: true, message: '请选择预计回院时间', trigger: 'change' }
  ],
  companionName: [
    { required: true, message: '请输入陪同人姓名', trigger: 'blur' }
  ],
  companionRelation: [
    { required: true, message: '请输入陪同人关系', trigger: 'blur' }
  ],
  companionPhone: [
    { required: true, message: '请输入陪同人电话', trigger: 'blur' }
  ]
}

function add(row) {
  formData.customerId = row.id
  formData.customerName = row.name
  formData.reason = ''
  formData.outTime = ''
  formData.expectedReturn = ''
  formData.companionName = ''
  formData.companionRelation = ''
  formData.companionPhone = ''
  drawerVisible.value = true
}

function submitForm() {
  // 先校验

  formRef.value.validate(async (valid) => {
    if (!valid) return
    const payload = {
      customerId: formData.customerId,
      reason: formData.reason,
      outTime: dayjs(formData.outTime).format('YYYY-MM-DD HH:mm:ss'),
      expectedReturn: dayjs(formData.expectedReturn).format('YYYY-MM-DD HH:mm:ss'),
      companionName: formData.companionName,
      companionRelation: formData.companionRelation,
      companionPhone: formData.companionPhone,
    }
    const { data: rb } = await axios.post(
      'OutRegistrationController/add',
      qs.stringify(payload)
    )
    if (rb.status === 200) {
      ElMessage.success('外出申请已提交')
      drawerVisible.value = false
      loadData()
    } else {
      ElMessage.error('提交失败：' + rb.message)
    }
  })
}
</script>

<style scoped>
.el-pagination {
  margin-top: 20px;
}
.table-title {
  background: #f5f5f5;
  padding: 8px;
  margin: 10px 0;
}
</style>
